<template>
  <a-form
    :form="form"
    v-bind="layout" 
    @submit="handleAddSubmit">
    <a-row >
      <a-col :span="16"  :offset="3">
        <a-form-item label="账号">
          <a-input
            style="width: 100%"
            v-decorator="[
              'username',
              {
                rules: [{ required: true, message: '请输入账号' }],
                initialValue: tempForm.username,
              },
            ]"
            placeholder="请输入账号"
          />
        </a-form-item>
      </a-col>
    </a-row>
    <a-row >
      <a-col :span="16"  :offset="3">
        <a-form-item label="姓名">
          <a-input
            v-decorator="[
              'name',
              {
                rules: [{ required: true, message: '请输入姓名' }],
                initialValue: tempForm.name,
              },
            ]"
            placeholder="请输入姓名"
          />
        </a-form-item>
      </a-col>
    </a-row>
    <a-row v-if="!tempForm.id">
      <a-col :span="16"  :offset="3">
        <a-form-item label="密码">
          <a-input
            style="width: 100%"
            type="password"
            v-decorator="[
              'password',
              {
                rules: [{  required: true, message: '请输入密码' }],
              },
            ]"
            placeholder="请输入密码"
          />
        </a-form-item>
      </a-col>
    </a-row>
    <a-row >
      <a-col :span="16"  :offset="3">
        <a-form-item label="电话">
          <a-input
            style="width: 100%"
            v-decorator="[
              'tel',
              {
                rules: [{validator: validateTel, trigger: 'blur'}],
                initialValue: tempForm.tel,
              },
            ]"
            placeholder="请输入电话"
          />
        </a-form-item>
      </a-col>
    </a-row>
    <a-row >
      <a-col :span="16"  :offset="3">
        <a-form-item label="团员">
          <a-select placeholder="请选择团员" 
              v-decorator="[
                'member_id',
                {
                  rules: [{ required: true, message: '请选择团员' }],
                  initialValue: tempForm.memberId,
                },
              ]">
            <a-select-option v-for="(item, index) in listData" :key="index" :value="item.id">{{ item.name }}</a-select-option>
          </a-select>
        </a-form-item>
      </a-col>
    </a-row>
    <a-row >
      <a-col :span="16"  :offset="3">
        <a-form-item label="邮箱">
          <a-input
            style="width: 100%"
            v-decorator="[
              'email',
              {
                rules: [{ required: true, message: '请输入邮箱' }],
                initialValue: tempForm.email,
              },
            ]"
            placeholder="请输入邮箱"
          />
        </a-form-item>
      </a-col>
    </a-row>
    <a-row >
      <a-col :span="16"  :offset="3">
        <a-form-item label="排序">
          <a-input type="number"
            style="width: 100%"
            v-decorator="[
              'sort',
              {
                rules: [{ required: true, message: '请输入排序' }],
                initialValue: tempForm.sort,
              },
            ]"
            placeholder="请输入排序"
          />
        </a-form-item>
      </a-col>
    </a-row>
  </a-form>
</template>

<script>
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result));
  reader.readAsDataURL(img);
}
function getBase64_2(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}
export default {
  name: "List",
  props: {
    tempForm: {
      type: Object,
      default: () => {
        return {}
      },
    }
  },
  data() {
    return {
       layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 18 },
      },
      form: {},
      imageUrl: "",
      photo: "",
      previewImage: "",
      currentRole: "",
      loading: false,
      previewVisible: false,
      listData: [],
    };
  },
  created() {
    if (this.tempForm && this.tempForm.id) {
      this.openUpdateForm();
      } else {
      this.openAddForm();
    }
  },
  mounted() {
    this.getList();
  },
  methods: {
    validateIdCard(rule, value, callback){
      if (!value || value.length !== 18) {
        callback(new Error('请输入正确的身份证号'));
      } else {
        callback();
      }
    },
    validateTel(rule, value, callback) {
      if (!value || value.length !== 11) {
        callback(new Error('请输入正确的电话号'));
      } else {
        callback();
      }
    },
    getList() {
      this.$ajax({
        url: this.$api.member.findList,
        data: {},
        success: (result) => {
          this.listData = result;
        },
        fail: (err) => {
          this.$message.success(err);
        },
      });
    },
    openAddForm() {
      this.form = this.$form.createForm(this, { name: "add" });
    },
    openUpdateForm(item) {
      this.form = this.$form.createForm(this, { name: "update" });
      this.photo = this.tempForm.avatar;
    },
    save() {
      if (this.tempForm && this.tempForm.id) {
        this.handleUpdateSubmit()
      } else {
        this.handleAddSubmit()
      }
    },
    handleAddSubmit(e) {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.$ajax({
            url: this.$api.system.user.addUser,
            data: Object.assign({ avatar: this.photo }, values),
            success: (result) => {
              this.$message.success("新增成功");
              this.$emit('pass', null);
            },
            fail: (err) => {
              this.$emit('reject', null);
            }
          });
        } else {
          console.log(err);
          this.$emit('reject', null);
        }
      });
    },
    handleUpdateSubmit(e) {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.$ajax({
            url: this.$api.system.user.updateUser,
            data: Object.assign(
              { id: this.tempForm.id, avatar: this.photo },
              values
            ),
            success: (result) => {
              this.$message.success("修改成功");
              this.$emit('pass', null);
            },
            fail: (err) => {
              this.$emit('reject', null);
            }
          });
        } else {
          console.log(err);
          this.$emit('reject', null);
        }
      });
    },
    remove(id) {
      this.$ajax({
        url: this.$api.system.user.deleteUser,
        data: { id },
        success: (result) => {
          this.$message.success("删除成功");
          this.$emit('pass', null);
        },
      });
    },
    handleChange(info) {
      if (info.file.status === "uploading") {
        this.loading = true;
        return;
      }
      if (info.file.status === "removed") {
        this.imageUrl = "";
        return;
      }
      if (info.file.status === "done") {
        // Get this url from response in real world.
        this.photo = info.file.response.data;
        getBase64(info.file.originFileObj, (imageUrl) => {
          this.imageUrl = imageUrl;
          this.loading = false;
        });
      }
    },
    beforeUpload(file) {
      const isJpgOrPng =
        file.type === "image/jpeg" || file.type === "image/png";
      if (!isJpgOrPng) {
        this.$message.error("You can only upload JPG file!");
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("Image must smaller than 2MB!");
      }
      return isJpgOrPng && isLt2M;
    },
    handleCancel() {
      this.previewVisible = false;
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64_2(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    showData(item) {
      this.tempForm = item;
      this.visibleForConfig = true;
      this.findUserRoleList();
    },
    handleRoleChange(value) {
      this.currentRole = value;
    },
  }, // methods
};
</script>
<style lang="less" scoped>
.ant-form-item-with-help {
    margin-bottom: 24px !important;
}
</style>